﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Type = System.Type;

namespace Medianamik.UI.Controls
{
    public class DropDownListManyToMany : BaseMedianamikControl
    {
        private readonly System.Web.UI.WebControls.DropDownList _dropDownList = new System.Web.UI.WebControls.DropDownList() { ID = ControlToValidateId };
        protected System.Web.UI.WebControls.DropDownList ManyToManyDropDownList
        {
            get { return _dropDownList; }
        }

        public override object GetValue()
        {
            EnsureChildControls();
            return new List<Guid> { _dropDownList.SelectedIndex > 0 ? new Guid(_dropDownList.SelectedValue) : default(Guid) };
        }

        public override Type TypeOfValue
        {
            get { return typeof(IEnumerable<Guid>); }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_dropDownList);

            if (pUseDataSource)
            {
                var selectedValues = DataSource as IEnumerable<Guid> ?? Enumerable.Empty<Guid>();

                if (Options.Count > 0)
                {
                    //La propriété est normalement identique pour toutes les options.
                    var propertyId = Options[0].PropertyId;
                    var optionNodes = NodeManager.GetNodes(Options.Select(o => o.NodeId).ToArray())
                        .OrderBy(n => n.Name);

                    foreach (var node in optionNodes.Where(n => !ControlInfo.TreeRootNodeID.HasValue ||
                                n.IsChildOf(ControlInfo.TreeRootNodeID.Value)))
                    {
                        ListItem item = BuildItems(node, propertyId);
                        _dropDownList.Items.Add(item);
                        item.Selected = selectedValues.Any(v => v.Equals(node.ID));
                    }
                }
                _dropDownList.Items.Insert(0, new ListItem("", Guid.Empty.ToString()));
            }
        }



        protected virtual ListItem BuildItems(Core.Node node, Guid propertyId)
        {
            return new ListItem(node.DefaultInstance[propertyId].GetValue<string>(),
                                node.ID.ToString());
        }

        public override void SetValue(object value)
        {
            EnsureChildControls();
            _dropDownList.SelectedValue = (string)value;
        }
    }

}
